<template>
  <div class="madoka" :class="{ is_transparency: Madoka.isTransparency }">
    <canvas :ref="Madoka.ref.set"></canvas>
  </div>
</template>
<script setup lang="ts">
import * as PIXI from "pixi.js";
import { Live2DModel } from "pixi-live2d-display";

const Madoka = (() => {
  const init = async () => {
    // 将 PIXI 暴露到 window 上，这样插件就可以通过 window.PIXI.Ticker 来自动更新模型
    (<any>window).PIXI = PIXI;
    const app = new PIXI.Application({
      view: s.ref.value,
      transparent: true
    });
    const model = await Live2DModel.from("./kami/model.model3.json");
    app.stage.addChild(model);

    // 变换
    model.x = 100;
    model.y = 100;
    model.rotation = Math.PI;
    model.skew.x = Math.PI;
    model.scale.set(0.2, 0.2);
    model.anchor.set(1.1, 0.192);

    // 交互
    model.on("hit", (hitAreas) => {
      if (hitAreas.includes("body")) {
        model.motion("tap_body");
      }
    });
  };
  const handleMouseMove = () => {
    const { x, y } = s.mouse;
    s.isTransparency = x + s.width > window.innerWidth && y + s.height > window.innerHeight;
  };

  const s = reactive({
    width: 300,
    height: 240,
    cssWidth: computed((): string => `${s.width}px`),
    cssHeight: computed((): string => `${s.height}px`),
    isTransparency: false,
    ref: {
      value: undefined as HTMLCanvasElement | undefined,
      set(v: any) {
        s.ref.value = v;
      }
    },
    mouse: useMouse()
  });

  onMounted(init);
  watch(() => s.mouse, handleMouseMove, { deep: true });

  return s;
})();

</script>
<style scoped lang="less">
.madoka {
  position: fixed;
  right: 0;
  bottom: 0;
  width: v-bind("Madoka.cssWidth");
  height: v-bind("Madoka.cssHeight");
  pointer-events: none;
  transition: 0.2s;
  //
  &.is_transparency {
    opacity: 0.1;
  }

  & > canvas {
    display: block;
    width: 100%;
    height: 100%;
  }
}

</style>